package cs575.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cs575.common.ConnectionThread;
import cs575.common.Player;
import cs575.common.Player.Position;

/**
 * Server class that listens for messages and passes them to the required
 * service.
 */
public class FantasyServer extends Thread {
	/**
	 * Maps a player's name to the player object containing its attributes and
	 * stats.
	 */
	public static HashMap<String, Player> PLAYERS = new HashMap<String, Player>();

	private ServerSocket server;
	private ServerParser parser;

	private boolean quit = false;

	public FantasyServer(int port) {
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}

		parser = new ServerParser();

		/* TESTING */
		HashMap<String, Integer> stats = new HashMap<String, Integer>();
		stats.put("Yards", 55);
		stats.put("TDs", 2);
		Player tim = new Player("Tim Hanna", Position.TE);
		tim.setStats(stats);

		stats = new HashMap<String, Integer>();
		stats.put("XP", 2);
		stats.put("FGs", 3);
		Player nate = new Player("Nate Durant", Position.K);
		nate.setStats(stats);
		PLAYERS.put("Tim Hanna", tim);
		PLAYERS.put("Nate Durant", nate);
	}

	public void run() {
		while (!quit) {
			try {
				Socket clientSocket = server.accept();
				if (clientSocket != null) {
					ConnectionThread ct = new ConnectionThread(clientSocket,
							parser);
					ct.start();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// Ignore.
			}
		}
	}

	public static synchronized void updatePlayerTable(Player player) {
		PLAYERS.put(player.getName(), player);

	}

	public static boolean doesPlayerExist(String name) {
		return PLAYERS.get(name) != null;
	}

	public static Player getPlayer(String name) {
		return PLAYERS.get(name);
	}

	public static List<Player> getAllPlayers() {
		return new ArrayList<Player>(PLAYERS.values());
	}

	public static void main(String[] args) {
		FantasyServer server = new FantasyServer(7777);
		server.start();
	}

}
